﻿//********************************************************************************//
//创建日期：<创建日期，2016-04-11>
//创建作者：<朱大鹏，朱大鹏@shanghai3h.com>
//modify:guodengjie last at 20170825
//功能说明：转换自来水公司数据
//********************************************************************************//
using System;
using Entity;
using BLL;
using BLL.Access;
using System.Data;
using Web.Class;
using System.IO;
using System.Data.Odbc;
using DevExpress.Web;
using System.Data.OleDb;
using System.Data.Common;

namespace Web.Pages.YongShui.ChaoBiaoKZ
{
    public partial class ZhuanHuanZLSGSSJ : BasePage
    {
        #region 属性
        public DataTable MyDataTable
        {
            get { return ViewState["MyDataTable"] == null ? null : ViewState["MyDataTable"] as DataTable; }
            set { ViewState["MyDataTable"] = value; }
        }
        /// <summary>
        /// 当前操作项ID
        /// </summary>
        private object YONGHUBHID
        {
            get
            {
                return ViewState["_YONGHUBHID"];
            }
            set
            {
                ViewState["_YONGHUBHID"] = value;
            }
        }
        private string WENJIANDZ
        {
            get
            {
                return ViewState["WENJIANDZ"]!=null?ViewState["WENJIANDZ"].ToString():"";
            }
            set
            {
                ViewState["WENJIANDZ"] = value;
            }
        }
        private string WENJIANMC
        {
            get
            {
                return ViewState["WENJIANMC"] != null ? ViewState["WENJIANMC"].ToString() : "";
            }
            set
            {
                ViewState["WENJIANMC"] = value;
            }
        }
        private string ALERTZT
        {
            get
            {
                return ViewState["ALERTZT"]!=null?ViewState["ALERTZT"].ToString():"";
            }
            set
            {
                ViewState["ALERTZT"] = value;
            }
        }
        /// <summary>
        /// 当前增加的水表ID(当增表时水表号已经存在时,记录)
        /// </summary>
        private int SHUIBIAOID
        {
            get
            {
                return Convert.ToInt32(ViewState["_SHUIBIAOID"]);
            }
            set
            {
                ViewState["_SHUIBIAOID"] = value;
            }
        }

        /// <summary>
        /// 记录查询结果集
        /// </summary>
        private DataTable dtSource
        {
            get
            {
                return ViewState["dtSource"] as DataTable;
            }
            set
            {
                ViewState["dtSource"] = value;
            }
        }

        /// <summary>
        /// 当前操作用户站点
        /// </summary>
        private string ZHANDIANBH
        {
            get
            {
                return Convert.ToString(ViewState["_ZHANDIANBH"]);
            }
            set
            {
                ViewState["_ZHANDIANBH"] = value;
            }
        }

        #endregion

        #region 变量

        /// <summary>
        /// 数据访问操作类
        /// </summary>
        SpHelper _spHelper = new SpHelper();

        YS_CB_HUIZONGCWBLL hzxxbll = new YS_CB_HUIZONGCWBLL();
        /// <summary>
        /// 水表信息对象
        /// </summary>
        YS_CB_SHUIBIAOXX _YS_CB_SHUIBIAOXX = new YS_CB_SHUIBIAOXX();

        //用户信息BLL
        YS_YG_YONGHUXXBLL _YS_YG_YONGHUXXBLL = new YS_YG_YONGHUXXBLL();

        /// <summary>
        /// 用户水表关系BLL
        /// </summary>
        YS_CB_YONGHUSBGXBLL _YS_CB_YONGHUSBGXBLL = new YS_CB_YONGHUSBGXBLL();

        /// <summary>
        /// 水表信息BLL
        /// </summary>
        YS_CB_SHUIBIAOXXBLL _YS_CB_SHUIBIAOXXBLL = new YS_CB_SHUIBIAOXXBLL();

        /// <summary>
        /// 日志BLL
        /// </summary>
        SYS_LOGBLL _SYS_LOGBLL = new SYS_LOGBLL();

        
        #endregion

        #region 事件
        
        /// <summary>
        /// 页面加载事件
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
           
            if (!IsPostBack)
            {
                BindgvCuoWuWJM();
                Session["MyFileDataTable"] = null;
            }
            gvWenJianGZ.DataSource = MyDataTable;
            gvWenJianGZ.DataBind();
        }
        /// <summary>
        /// 转换数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnZhuanHuanSJ_Click(object sender, EventArgs e)
        {
            
            try
            {
                SaveZLSData(0);


                if (Convert.ToInt32(ALERTZT) == 1)
                {
                    PageTools.AlertMsg(this, "转换完成");
                }
                else if (Convert.ToInt32(ALERTZT) == 2)
                {
                    PageTools.AlertMsg(this, "文件没有找到命名规则");
                }
                else if (Convert.ToInt32(ALERTZT) == 3)
                {
                    PageTools.AlertMsg(this, "文件年月错误");
                }
                else if (Convert.ToInt32(ALERTZT) == 4)
                {
                    PageTools.AlertMsg(this, "请选择文件");
                }
                else
                {
                    PageTools.AlertMsg(this, "转换失败");
                }
                ALERTZT = "0";
                this.Status = GridViewStatus.Init;
                Display();
            }
            catch (Exception ex)
            {
                txtZhuanHuanJG.Text = ex.Message;
            }
        }
        protected void Call_Callback(object source, DevExpress.Web.CallbackEventArgs e)
        {
            if (e.Parameter == "zhuanhuansjcheck")
            {
                e.Result = e.Parameter + "|" + CheckValue(0);
            }
            if (e.Parameter == "zhuanhuanlssjcheck")
            {
                e.Result = e.Parameter + "|" + CheckValue(1);
            }
            if (e.Parameter == "zhsj")
            {
                e.Result = e.Parameter + "|" + GetUpLoadValue();
            }
            if (e.Parameter == "cbsj_dxs")
            {
                e.Result = e.Parameter + "|" + TransferWaterDataToDXS();
            }
            
        }
        /// <summary>
        /// 查看转换日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnChaKan_Click(object sender, EventArgs e)
        {
            
            MyDataTable = _spHelper.P_YS_CB_ZILAISGSSJZHRZ().Tables[0];
            gvWenJianGZ.SettingsPager.Mode = GridViewPagerMode.EndlessPaging;
            gvWenJianGZ.SettingsPager.PageSize = 80;
            gvWenJianGZ.DataSource = MyDataTable;
            gvWenJianGZ.DataBind();
            if (this.Status == GridViewStatus.Search)
            {
                this.Status = GridViewStatus.Init;
            }
            else
            {
                this.Status = GridViewStatus.Search;
            }
            
            Display();
        }
        /// <summary>
        /// 转换历史数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnZhuanHuanLSSJ_Click(object sender, EventArgs e)
        {
            try
            {
                SaveZLSData(1);
                if (Convert.ToInt32(ALERTZT) == 1)
                {
                    PageTools.AlertMsg(this, "转换完成");
                }
                else if (Convert.ToInt32(ALERTZT) == 2)
                {
                    PageTools.AlertMsg(this, "文件没有找到命名规则");
                }
                else if (Convert.ToInt32(ALERTZT) == 3)
                {
                    PageTools.AlertMsg(this, "文件年月错误");
                }
                else if (Convert.ToInt32(ALERTZT) == 4)
                {
                    PageTools.AlertMsg(this, "请选择文件");
                }
                else if (Convert.ToInt32(ALERTZT) == 5)
                {
                    PageTools.AlertMsg(this, "选择文件非历史数据");
                }
                else
                {
                    PageTools.AlertMsg(this, "转换失败");
                }
                ALERTZT = "0";
                this.Status = GridViewStatus.Init;
                Display();
            }
            catch (Exception ex)
            {
                txtZhuanHuanJG.Text = ex.Message;
            }
        }
       
        /// <summary>
        /// 上传文件   并且批量插入数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void UpLoadFile_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
        {
            GC.Collect();

            if (e.UploadedFile.IsValid)
            {
                //Response.Write(e.UploadedFile.FileName);
                string wjmc = e.UploadedFile.FileName;
                string filePath = Path.Combine(Server.MapPath("/UPLOAD/CB"), wjmc.Replace(Path.GetExtension(e.UploadedFile.FileName), "") + Path.GetExtension(e.UploadedFile.FileName));    //文件完整物理路径
                try
                {
                    e.UploadedFile.SaveAs(filePath);
                }
                catch (Exception ex)
                {
                    Session["WENJIANMC"] = "";
                    Session["WENJIANDZ"] = "";
                    e.CallbackData = "-1";
                    e.ErrorText = ex.Message;
                    GC.Collect();
                    return;
                }
                GC.Collect();
                int type = Convert.ToInt32(HidList.Get("type"));

                if (Session["MyFileDataTable"] != null)
                {
                    DataTable dt = Session["MyFileDataTable"] as DataTable;
                    DataRow dr = dt.NewRow();
                    dr["name"] = e.UploadedFile.FileName;
                    dr["path"] = filePath;
                    dr["type"] = type;
                    dt.Rows.Add(dr);
                    Session["MyFileDataTable"] = dt;
                }
                else
                {
                    DataTable dt = new DataTable();
                    dt.Columns.Add("name");
                    dt.Columns.Add("path");
                    dt.Columns.Add("type");

                    DataRow dr = dt.NewRow();
                    dr["name"] = e.UploadedFile.FileName;
                    dr["path"] = filePath;
                    dr["type"] = type;
                    dt.Rows.Add(dr);
                    Session["MyFileDataTable"] = dt;
                }



                e.CallbackData = "文件("+e.UploadedFile.FileName+")上传完成\r";
               // e.CallbackData = SaveDataByFileName(wjmc,filePath,type);
                //string wjmc = UpLoadFile.FileName;
                //WENJIANMC = wjmc;
                //Session["WENJIANMC"] = wjmc;


                //string filePath = Path.Combine(Server.MapPath("/UPLOAD/CB"), wjmc.Replace(Path.GetExtension(e.UploadedFile.FileName),"") + Path.GetExtension(e.UploadedFile.FileName));    //文件完整物理路径
                //UpLoadFile.SaveAs(filePath);
                //WENJIANDZ = filePath;
                //Session["WENJIANDZ"] = filePath;
                //e.CallbackData = "1";
            }
            else
            {
                Session["WENJIANMC"] = "";
                Session["WENJIANDZ"] = "";
                e.CallbackData = "-1";
                return;
            }
        }

        #endregion

        #region 方法

        /// <summary>
        /// SqlDataReader 转成 DataTable
        /// 源需要是结果集
        /// </summary>
        /// <param name="dataReader"></param>
        /// <returns></returns>
        private static DataTable ConvertDataReaderToDataTable(DbDataReader dataReader, int iMax = 300000)
        {
            ///定义DataTable  
            DataTable datatable = new DataTable();
            datatable.TableName = "From";
            DataRow myDataRow = null;
            string sVal = "";

            if (!dataReader.IsClosed)
            try
            {    ///动态添加表的数据列  
                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    DataColumn myDataColumn = new DataColumn();
                    myDataColumn.ColumnName = dataReader.GetName(i).ToUpper();
                    //myDataColumn.DataType = dataReader.GetFieldType(i);
                    var vType = dataReader.GetFieldType(i);
                    if ("N_YSJ" == myDataColumn.ColumnName.ToUpper() && Type.GetType("System.Decimal") == vType)
                        myDataColumn.DataType = System.Type.GetType("System.Decimal");
                    else if (("QM" == myDataColumn.ColumnName || "C_ID" == myDataColumn.ColumnName
                        || "C_CH" == myDataColumn.ColumnName || "C_KH" == myDataColumn.ColumnName
                        || "C_BFL" == myDataColumn.ColumnName || "C_YSDM" == myDataColumn.ColumnName
                        || "C_XZQ" == myDataColumn.ColumnName || "C_ZBH" == myDataColumn.ColumnName
                        || "C_ZHBH" == myDataColumn.ColumnName
                        ) && Type.GetType("System.Decimal") == vType)
                    {
                        myDataColumn.DataType = System.Type.GetType("System.String");
                        myDataColumn.MaxLength = 50;
                    }
                    else if (Type.GetType("System.Decimal") == vType)
                        myDataColumn.DataType = System.Type.GetType("System.Int32");
                    else if (Type.GetType("System.DateTime") == vType)
                        myDataColumn.DataType = System.Type.GetType("System.DateTime");
                    else
                    {
                        myDataColumn.DataType = System.Type.GetType("System.String");
                        myDataColumn.MaxLength = 500;
                    }
                    datatable.Columns.Add(myDataColumn);
                }

                ///添加表的数据
                for (int c = 0;  dataReader.Read() && c < iMax; ++c)
                {
                    myDataRow = datatable.NewRow();
                    for (int i = 0; i < dataReader.FieldCount; ++i)
                    {
                            if (!dataReader.IsDBNull(i))
                                sVal = dataReader[i].ToString().Trim();
                            decimal fVal = 0;
                            string sFieldName = datatable.Columns[i].ColumnName;
                            var vType = datatable.Columns[i].DataType;
                            if (Type.GetType("System.Decimal") == vType)
                            {
                                decimal.TryParse(sVal, out fVal);
                                myDataRow[i] = fVal;
                            }
                            else if (Type.GetType("System.Int32") == vType)
                            {
                                decimal.TryParse(sVal, out fVal);
                                myDataRow[i] = Convert.ToInt32(fVal);
                            }
                            else if (Type.GetType("System.DateTime") == vType)
                            {
                                DateTime dt = Convert.ToDateTime("1900-01-01");
                                DateTime.TryParse(sVal, out dt);
                                myDataRow[i] = dt;
                            }
                            else myDataRow[i] = sVal;
                        }
                    datatable.Rows.Add(myDataRow);
                    myDataRow = null;
                }
            }
            catch (Exception ex)
            {
                ///抛出类型转换错误  
                //SystemError.CreateErrorLog(ex.Message);  
                throw new Exception(ex.Message + "\r\n编号：" + myDataRow[3].ToString() + " \t\t 值：" + sVal, ex);
            }
            return datatable;
        }

        private string TransferWaterDataToDXS()
        {
            int? code;
            string msg;
            new SpHelper().P_YSCB_CBSJCC(LoginInfo.CurrentUser.UserID, out code, out msg);
            return code + "|" + msg;            
        }
        private string GetUpLoadValue()
        {
            int count = 0;
            string msg = "";
            if (Session["MyFileDataTable"] == null)
            {
                msg = count+"|"+"结束";
                return msg;
            }
            DataTable dt = Session["MyFileDataTable"] as DataTable;

            if (dt == null || dt.Rows.Count == 0)
            {
                msg = count + "|" + "结束";
                return msg;
            }

            string name = dt.Rows[0]["name"].ToString();
            string path = dt.Rows[0]["path"].ToString();
            int type = Convert.ToInt32(dt.Rows[0]["type"]);

            msg = SaveDataByFileName(name,path,type);

            DataTable newdt = dt.Clone();

            for (int i = 1; i < dt.Rows.Count; i++)
            {
                DataRow newdr = newdt.NewRow();

                newdr[0] = dt.Rows[i][0];
                newdr[1] = dt.Rows[i][1];
                newdr[2] = dt.Rows[i][2];

                newdt.Rows.Add(newdr);
            }
            count= newdt.Rows.Count;
            if (newdt.Rows.Count == 0)
            {
                newdt = null;
                
            }
            Session["MyFileDataTable"] = newdt;
            return count+"|"+msg;
        }
        private string SaveDataByFileName(string filename,string filepath,int type)
        {
            GC.Collect();
            DateTime dtBegin = DateTime.Now;

            string msg = "";
            if (filename.Trim().Length == 0 || filepath.Trim().Length == 0)
            {
                msg = filename+"：文件名称错误";
            }

            string ym = BusinessTool.YS_GETSETTINGSVALUE(eSETTINGS_KEYNAME.WATER_Y_M.ToString());
            string wjmc = filename;
            string filePath = filepath;

           
            int outint = 0;
            if (!int.TryParse(wjmc.Substring(2, 4), out outint))
            {
                msg = filename+"：文件年月格式错误";               
                
            }
            if (wjmc.Remove(wjmc.LastIndexOf('.')).Trim().Length != ym.Length)
            {
                msg = filename + "：文件年月格式错误";               
            }
            if (wjmc.Substring(2, 4) != ym.Substring(2, 4) && type == 0)
            {
                msg = filename + "：文件年月格式错误";   
                
            }
            if (type == 1 && wjmc.Substring(2, 4) == ym.Substring(2, 4))
            {
                msg = filename + "：文件年月格式错误";   
               
            }
            if (msg != "")
            {
                return msg+"\r";
            }
            if (type == 1)
            {
                ym = ym.Substring(0, 2) + wjmc.Substring(2, 4);
            }
            using (OdbcConnection oConn = new System.Data.Odbc.OdbcConnection())
            //using (OleDbConnection oConn = new OleDbConnection())
            {
                //oConn.ConnectionString = "Driver={Microsoft dBase Driver (*.dbf)};DefaultDir=" + Server.MapPath("/UPLOAD/CB");
               oConn.ConnectionString = "Driver={Microsoft FoxPro VFP Driver (*.dbf)};UID=;SourceType=DBF;SourceDB=" + Server.MapPath("/UPLOAD/CB");
                //oConn.ConnectionString = "Provider=VFPOLEDB.1;Data Source=" + Server.MapPath("/UPLOAD/CB") + ";Collating Sequence=MACHINE;Exclusive=NO;TABLEVALIDATE=0";
                oConn.Open();
                string strComm = "select * from  [" + Path.GetFileNameWithoutExtension(filePath) + "]";
                //OdbcDataAdapter odbcDataAdapt = new OdbcDataAdapter(strComm, oConn.ConnectionString);
                //OleDbDataAdapter odbcDataAdapt = new OleDbDataAdapter(strComm, oConn);
                OdbcCommand odbcDataAdapt = new OdbcCommand(strComm, oConn);
                OdbcDataReader dbRd = odbcDataAdapt.ExecuteReader();
                //OleDbCommand odbcDataAdapt = new OleDbCommand(strComm, oConn);
                //OleDbDataReader dbRd = odbcDataAdapt.ExecuteReader();

                //DataTable dtData = new DataTable();
                //dtData.TableName = "gb";
                //odbcDataAdapt.Fill(dtData);
                //dtData.Load(dbRd);

                try
                {
                    //if (dtData != null && dtData.Rows.Count > 0)
                    //if (dbRd.HasRows)
                    {                        
                        if (wjmc.Trim().Length > 2)
                        {
                            string sGongS = wjmc.Substring(0, 2).ToUpper();
                            string tablename = "";
                            string SuanFa = "";
                            string GUANLIK = "";
                            string gsmc = "";
                            DataTable ds = _spHelper.P_YS_CB_GONGSIBM(sGongS, out SuanFa, out GUANLIK, out tablename).Tables[0];
                           
                            gsmc = SuanFa;
                            if (SuanFa.Trim().Length > 0)
                            {
                                SuanFa = SuanFa.Substring(0, 4);
                            }
                            if (tablename.Trim().Length > 0)
                            {
                                bool bHasData = false;


                                #region 插入临时表
                                for (DataTable dtData = ConvertDataReaderToDataTable(dbRd);  dtData != null && dtData.Rows.Count > 0;  dtData = ConvertDataReaderToDataTable(dbRd))
                                {
                                    bHasData = true;
                                    DataTable newdt = new DataTable();
                                    newdt.TableName = "to";

                                    foreach (DataColumn d in dtData.Columns)
                                    {
                                        // 添加字段
                                        Action<string> addCol = (sName) =>
                                        {
                                            DataColumn newCol = new DataColumn();
                                            newCol.ColumnName = sName;
                                            newCol.DataType = d.DataType;
                                            newdt.Columns.Add(newCol);
                                        };

                                        if (ds.Columns.Contains(d.ColumnName) || d.ColumnName.ToLower().Trim() == "year" || d.ColumnName.ToLower().Trim() == "month")
                                        {
                                            if (d.ColumnName.ToLower().Trim() == "year")
                                            {
                                                if ("PD" != sGongS) addCol("I_Y");
                                            }
                                            else if (d.ColumnName.ToLower().Trim() == "month")
                                            {
                                                if ("PD" != sGongS) addCol("I_M");
                                            }
                                            else if (d.ColumnName.ToLower().Trim() == "qm")
                                                addCol("PD" == sGongS ? "C_ST" : d.ColumnName.ToUpper());
                                            else if (d.ColumnName.ToLower().Trim() == "d_cb")
                                            {
                                                addCol(d.ColumnName.ToUpper());
                                                if (SuanFa == "市北公司") newdt.Columns.Add("D_ZB");
                                            }
                                            else addCol(d.ColumnName.ToUpper());
                                        }

                                    }
                                    if ("PD" == sGongS)
                                    {
                                        newdt.Columns.Add("C_XZTJ");
                                        newdt.Columns.Add("C_XZBZ");
                                    }
                                    if ("CT" == sGongS)
                                    {
                                        newdt.Columns.Add("C_FWDH");
                                    }

                                    if (!newdt.Columns.Contains("C_DEPT"))
                                        newdt.Columns.Add("C_DEPT");

                                    foreach (DataRow dr in dtData.Rows)
                                    {
                                        DataRow newdr = newdt.NewRow();
                                        foreach (DataColumn d in newdt.Columns)
                                        {
                                            if (d.ColumnName.ToLower().Trim() != "c_dept")
                                            {
                                                if (d.ColumnName.ToLower().Trim() == "d_cb")
                                                {
                                                    newdr[d.ColumnName] = dr[d.ColumnName] == DBNull.Value ? null : Convert.ToDateTime(dr[d.ColumnName]).ToString("yyyy-MM-dd");
                                                }
                                                else if ("PD" == sGongS && d.ColumnName.ToLower().Trim() == "c_xztj")
                                                {
                                                    newdr[d.ColumnName] = "0";
                                                }
                                                else if ("PD" == sGongS && d.ColumnName.ToLower().Trim() == "c_xzbz")
                                                {
                                                    newdr[d.ColumnName] = "0";
                                                }
                                                else if ("CT" == sGongS && d.ColumnName.ToLower().Trim() == "c_fwdh")
                                                {
                                                    newdr[d.ColumnName] = dr["C_ID"];
                                                }
                                                else if (d.ColumnName.ToLower().Trim() != "d_zb")
                                                {
                                                    if ("PD" == sGongS)
                                                        newdr[d.ColumnName] = dr[d.ColumnName.ToLower().Replace("i_y", "year").Replace("i_m", "month").Replace("c_st", "qm").Replace("c_jh", "C_YSDM")].ToString().Trim();
                                                    else if ("CS" == sGongS)
                                                        newdr[d.ColumnName] = dr[d.ColumnName.ToLower().Replace("i_y", "year").Replace("i_m", "month")].ToString().Trim();
                                                    else
                                                        newdr[d.ColumnName] = dr[d.ColumnName.ToLower().Replace("i_y", "year").Replace("i_m", "month").Replace("c_jh", "C_YSDM")].ToString().Trim();
                                                }
                                                else
                                                {
                                                    newdr[d.ColumnName] = null;
                                                }
                                            }
                                            else
                                            {
                                                string sDept = wjmc.Substring(0, 2).ToLower();
                                                newdr["C_DEPT"] = sDept;
                                                if (sDept == "pd" || sDept == "ct")
                                                    newdr["C_DEPT"] += dr["C_XZQ"].ToString().Trim();
                                            }
                                        }
                                        newdt.Rows.Add(newdr);
                                    }

                                    /*
                                    //判断 服务点编号是否存在 
                                    for(int i = 0; i < newdt.Rows.Count; i++)
                                    {
                                        string c_id = newdt.Rows[i]["c_id"].ToString();
                                        string c_zhbh = newdt.Rows[i]["c_zhbh"].ToString();
                                        string c_kj = newdt.Rows[i]["c_kj"].ToString();
                                        string c_dz = newdt.Rows[i]["c_dz"].ToString();
                                        string c_hm = newdt.Rows[i]["c_hm"].ToString();
                                        string c_ysdm = newdt.Rows[i]["c_jh"].ToString();
                                        _spHelper.P_YS_CB_ISEXISTSBH(c_id, c_zhbh, c_kj, c_dz, c_hm, c_ysdm);
                                    }
                                    */

                                    DataSet qktable = _spHelper.P_YS_CB_QINGKONGB(tablename);
                                    //if (BusinessTool.InsertOracelData(newdt, tablename))
                                    //{
                                    //    int? errcode = 0;
                                    //    string errmsg = "";
                                    //    string show = "";
                                    //    if (SuanFa == "城投公司")
                                    //    {
                                    //        SuanFa = "市北公司";
                                    //    }
                                    //    DataSet zh = _spHelper.P_YS_CB_ZHUANGHUANZLSGSSJ(SuanFa, Convert.ToInt32(ym.Substring(0, 4)), Convert.ToInt32(ym.Substring(4, 2)), GUANLIK, out errcode, out errmsg);
                                    //    txtZhuanHuanJG.Text = gsmc.Trim() + " 转换完成。";

                                    //    msg =  gsmc.Trim().Remove(0,4)+" 转换完成";
                                    //}
                                    //else
                                    //{
                                    //    msg = "转换失败";

                                    //}
                                    BusinessTool.InsertOracelDataThrow(newdt, tablename);
                                }
                                #endregion 插入临时表

                                int? errcode = 0;
                                string errmsg = "";
                                string show = "";
                                if (SuanFa == "城投公司")
                                {
                                    SuanFa = "市北公司";
                                }

                                if (bHasData)
                                {
                                    DataSet zh = _spHelper.P_YS_CB_ZHUANGHUANZLSGSSJ(SuanFa, Convert.ToInt32(ym.Substring(0, 4)), Convert.ToInt32(ym.Substring(4, 2)), GUANLIK, out errcode, out errmsg);

                                    TimeSpan ts = DateTime.Now.Subtract(dtBegin);
                                    string sFinshInfo = " 转换完成，历时" + ts.Seconds + "秒。";
                                    txtZhuanHuanJG.Text = gsmc.Trim() + sFinshInfo;

                                    msg = gsmc.Trim().Remove(0, 4) + sFinshInfo;
                                }
                            }
                            else
                            {
                                msg = "对应文件没有找到命名规则";
                               
                            }
                        }

                    }
                }
                catch(Exception ex)
                {
                    msg = ex.Message;
                }
                finally
                {
                    dbRd.Close();
                    odbcDataAdapt.Dispose();
                    oConn.Dispose();
                    oConn.Close();
                }
            }
            GC.Collect();
            return filename +"："+msg+"\r";
        }
       

        /// <summary>
        ///用于控制控件的显示
        /// </summary>
        private void Display()
        {
            switch (this.Status)
            {
                case GridViewStatus.Init://转换
                    divZhuanHuanJG.Visible = true;
                    divWenJianGZ.Visible = false;
                    btnChaKan.Text = "查看";
                    btnChaKan.Enabled = true;
                    break;
                case GridViewStatus.Search://查看
                    
                    divWenJianGZ.Visible = true;
                    divZhuanHuanJG.Visible = false;
                    btnChaKan.Text = "退出查看";
                    //btnChaKan.Enabled = false;
                    break;
                case GridViewStatus.Add://错误
                    divZhuanHuanJG.Visible = false;
                    divWenJianGZ.Visible = false;
                   
                    btnChaKan.Enabled = true;
                    break;
            }
        }
        /// <summary>
        /// 转换数据
        /// </summary>
        /// <param name="type">0转换数据  1转换历史数据</param>
        private void SaveZLSData(int type)
        {
            return;
            if (Session["WENJIANMC"] == null || Session["WENJIANDZ"] == null)
            {
                ALERTZT = "4";
                return;
            }
            string wjmc = Session["WENJIANMC"].ToString();
            string filePath = Session["WENJIANDZ"].ToString();

            string ym = BusinessTool.YS_GETSETTINGSVALUE(eSETTINGS_KEYNAME.WATER_Y_M.ToString());
            int outint = 0;
            if (!int.TryParse(wjmc.Substring(2, 4),out outint))
            {
                ALERTZT = "3";//文件年月错误
                return;
            }
            if (wjmc.Remove(wjmc.LastIndexOf('.')).Trim().Length != ym.Length)
            {
                ALERTZT = "3";//文件年月错误
                return;
            }
            if (wjmc.Substring(2, 4) != ym.Substring(2, 4) && type == 0)
            {
                ALERTZT = "3";//文件年月错误
                return;
            }
            if (type == 1&&wjmc.Substring(2, 4) == ym.Substring(2, 4))
            {
                ALERTZT = "5";//文件年月错误
                return;                
            }
            
            if (type == 1)
            {
                ym = ym.Substring(0, 2) + wjmc.Substring(2, 4);
            }
            using (OdbcConnection oConn = new System.Data.Odbc.OdbcConnection())
            {
                oConn.ConnectionString = "Driver={Microsoft dBase Driver (*.dbf)};DefaultDir=" + Server.MapPath("/UPLOAD/CB");
                oConn.Open();
                OdbcDataAdapter odbcDataAdapt = new OdbcDataAdapter("select * from  [" + Path.GetFileNameWithoutExtension(filePath) + "]", oConn.ConnectionString);
                DataTable dtData = new DataTable();
                dtData.TableName = "gb";
                odbcDataAdapt.Fill(dtData);
                try
                {

                    if (dtData != null && dtData.Rows.Count > 0)
                    {
                        //WriteTXT(dtData);
                        if (wjmc.Trim().Length > 2)
                        {
                            string tablename = "";
                            string SuanFa = "";
                            string GUANLIK = "";
                            string gsmc = "";
                            DataTable ds = _spHelper.P_YS_CB_GONGSIBM(wjmc.Substring(0, 2).ToUpper(), out SuanFa, out GUANLIK, out tablename).Tables[0];
                            //SuanFa = "市北公司";
                            //tablename = "ys_temp_cb_zhilaisgssj_sb";
                            DataTable newdt = new DataTable();
                            gsmc = SuanFa;
                            if (SuanFa.Trim().Length > 0)
                            {
                                SuanFa = SuanFa.Substring(0, 4);
                            }
                            if (tablename.Trim().Length > 0)
                            {
                                foreach (DataColumn d in dtData.Columns)
                                {
                                    if (ds.Columns.Contains(d.ColumnName) || d.ColumnName.ToLower().Trim() == "year" || d.ColumnName.ToLower().Trim() == "month")
                                    {
                                        if (d.ColumnName.ToLower().Trim() == "year")
                                        {
                                            newdt.Columns.Add("I_Y");
                                        }
                                        else if (d.ColumnName.ToLower().Trim() == "month")
                                        {
                                            newdt.Columns.Add("I_M");
                                        }
                                        else if (d.ColumnName.ToLower().Trim() == "d_cb")
                                        {
                                            newdt.Columns.Add(d.ColumnName);
                                            if (SuanFa == "市北公司")
                                            {
                                                newdt.Columns.Add("D_ZB");
                                            }
                                        }
                                        else
                                        {
                                            newdt.Columns.Add(d.ColumnName);
                                        }
                                    }


                                }
                                if (!newdt.Columns.Contains("C_DEPT"))
                                {
                                    newdt.Columns.Add("C_DEPT");
                                }
                                foreach (DataRow dr in dtData.Rows)
                                {
                                    DataRow newdr = newdt.NewRow();
                                    foreach (DataColumn d in newdt.Columns)
                                    {
                                        if (d.ColumnName.ToLower().Trim() != "c_dept")
                                        {
                                            if (d.ColumnName.ToLower().Trim() == "d_cb")
                                            {
                                                newdr[d.ColumnName] = Convert.ToDateTime(dr[d.ColumnName]).ToString("yyyy-MM-dd");
                                            }
                                            else if (d.ColumnName.ToLower().Trim() != "d_zb")
                                            {
                                                newdr[d.ColumnName] = dr[d.ColumnName.Replace("I_Y", "year").Replace("I_M", "month")];
                                            }

                                            else
                                            {
                                                newdr[d.ColumnName] = null;
                                            }
                                        }
                                        else
                                        {
                                            newdr["C_DEPT"] = wjmc.Substring(0, 2).ToLower();
                                        }
                                    }

                                    newdt.Rows.Add(newdr);
                                }
                                DataSet qktable = _spHelper.P_YS_CB_QINGKONGB(tablename);
                                if (BusinessTool.InsertOracelData(newdt, tablename))
                                {

                                    ALERTZT = "1";//转换完成

                                    int? errcode = 0;
                                    string errmsg = "";
                                    string show = "";
                                    if(SuanFa=="城投公司")
                                    {
                                        SuanFa = "市北公司";
                                    }
                                    DataSet zh = _spHelper.P_YS_CB_ZHUANGHUANZLSGSSJ(SuanFa, Convert.ToInt32(ym.Substring(0, 4)), Convert.ToInt32(ym.Substring(4, 2)), GUANLIK, out errcode, out errmsg);
                                    txtZhuanHuanJG.Text = gsmc.Trim() + " 转换完成。";

                                }
                                else
                                {
                                    ALERTZT = "-1";//转换失败

                                }
                            }
                            else
                            {
                                ALERTZT = "2";//文件没有找到命名规则
                            }
                        }

                    }
                }
                catch
                {

                }
                finally
                {
                    odbcDataAdapt.Dispose();
                    oConn.Dispose();
                    oConn.Close();
                }
            }

        }

        /// <summary>
        /// 绑定转换错误下拉框
        /// </summary>
        private void BindgvCuoWuWJM()
        {
            string ym = BusinessTool.YS_GETSETTINGSVALUE(eSETTINGS_KEYNAME.WATER_Y_M.ToString());            
            if (ym.Trim().Length == 6)
            {
                
                lblNianYue.Value = ym.Substring(0,4)+"年"+ym.Substring(4,2)+"月";
            }
           
        }
        public string CheckValue(int type)
        {
            string msg = "";
            if (Session["WENJIANMC"] == null || Session["WENJIANDZ"] == null)
            {
                msg = "-4|请选择上传文件";
                return msg;
            }
            string wjmc = Session["WENJIANMC"].ToString();
            string filePath = Session["WENJIANDZ"].ToString();

            string ym = BusinessTool.YS_GETSETTINGSVALUE(eSETTINGS_KEYNAME.WATER_Y_M.ToString());
            int outint = 0;
            if (!int.TryParse(wjmc.Substring(2, 4), out outint))
            {
                msg = "-3|文件年月格式错误";//文件年月错误
                return msg;
            }
            if (wjmc.Remove(wjmc.LastIndexOf('.')).Trim().Length != ym.Length)
            {
                msg = "-3|文件年月格式错误";//文件年月错误
                return msg;
            }
            if (wjmc.Substring(2, 4) != ym.Substring(2, 4) && type == 0)
            {
                msg = "-3|有无效年月记录";//文件年月错误
                return msg;
            }
            if (type == 1 && wjmc.Substring(2, 4) == ym.Substring(2, 4))
            {
                msg = "-5|上传文件非历史年月";//文件年月错误
                return msg;
            }
            string tablename = "";
            string SuanFa = "";
            string GUANLIK = "";

            DataTable ds = _spHelper.P_YS_CB_GONGSIBM(wjmc.Substring(0, 2).ToUpper(), out SuanFa, out GUANLIK, out tablename).Tables[0];
            if (tablename.Trim() == "")
            {
                msg = "-3|文件没有找到命名规则";
                return msg;
            }
            msg = "1|操作成功";
            return msg;
        }
        #endregion
    }
}